package com.jfsnpm.authority;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfsnpm.common.AppSql;

public class Authority {
	private String userId;
	private boolean isAdmin=false;
	
	/**
	 * 传入userid初始化
	 * @param id String 用户id
	 */
	public Authority(String id){
		if(StringUtils.isBlank(id)){
			this.setUserId("");
		}else{
			this.setUserId(id);
			if(id.equals("admin")){
				this.setAdmin(true);
			}
		}
	}
	/**
	 * 传入Controller初始化
	 * @param me Controller 当前Controller
	 */
	public Authority(Controller me){
		String id = me.getSessionAttr("userid");
		if(StringUtils.isBlank(id)){
			this.setUserId("");
		}else{
			this.setUserId(id);
			if(id.equals("admin")){
				this.setAdmin(true);
			}
		}
	}
	/**
	 * 获取有权限的系统列表
	 * @return 系统列表 Map<String,List<Record>> 
	 * 								<系统列表,系统List>
	 * 								<系统1ID,系统菜单List>
	 * 								<系统2ID,系统菜单List>
	 * 								...
	 */
	public Map<String,List<Record>> getSystem(){
		Map<String,List<Record>> returnmap = new HashMap<String, List<Record>>();
		List<Record> systemlist = new ArrayList<Record>();
		List<Record> systemmenu = new ArrayList<Record>();
		if(isAdmin){
			systemlist = Db.find(AppSql.getsql("pm.getSystemIsAdmin"),"-root","禁用");
		}else{
			systemlist = Db.find(AppSql.getsql("pm.getSystem"),this.getUserId(),"-root","禁用");
		}
		returnmap.put("系统列表",systemlist);
		for(Record system:systemlist){
			if(isAdmin){
				systemmenu = Db.find(AppSql.getsql("pm.getSystemListIsAdmin"),"-root",system.getStr("system"),"禁用");
			}else{
				systemmenu = Db.find(AppSql.getsql("pm.getSystemList"),"-root",this.getUserId(),system.getStr("system"),"禁用");
			}
			returnmap.put(system.getStr("id"), systemmenu);
		}
		return returnmap;
	}
	
	/**
	 * 获取当前用户的常用菜单
	 * @return
	 */
	public List<Record> getTopten(){
		return Db.find(AppSql.getsql("pm.getTopTen"), this.getUserId(),"");
	}


	
	
	
	
	
	
	
	public String getUserId() {
		return userId;
	}
	public void setUserId(String userId) {
		this.userId = userId;
	}

	public boolean isAdmin() {
		return isAdmin;
	}

	public void setAdmin(boolean isAdmin) {
		this.isAdmin = isAdmin;
	}
	


}
